#include "TFKLineReqHandler.h"
#include <tfbondlib/tds/TfKLineRealTime_1M.h>
#include <QJsonArray>
#include <QJsonValue>
#include <QJsonObject>
#include <QJsonDocument>

TFKLineReqHandler::TFKLineReqHandler():TdsCmdHandler(KServerReq)
{
	connect(&TfKLineRealTime_1M::instance(), &TfKLineRealTime_1M::kLineReqDataArrived, this, &TFKLineReqHandler::onkLineReqDataArrived);
}

bool TFKLineReqHandler::processCmd(const QJsonObject& cmdObj, const ReqInfo& reqinfo, bool unReg /*= false*/)
{
	if (!parse(cmdObj))
		return false;

	m_reqs.insert({ m_id, reqinfo });
	TfKLineRealTime_1M::instance().getKLine1M(m_id.c_str());
	return true;
}

void TFKLineReqHandler::onkLineReqDataArrived(QString id, int beginIndex, int endIndex)
{
	if (m_reqs.find(id.toStdString()) == m_reqs.end())
		return;

	std::vector<QString> res;
	std::vector<xQBTFRealTimeUnit_c> data;
	if (!TfKLineRealTime_1M::instance().getRealtime(id.toUtf8().data(), data))
		return;

	QJsonArray jsList;
	QJsonObject jsRes;
	int count = 0;
	for (const auto& unit : data)
	{
		QJsonObject item;
		item["id"] = unit.m_TF_ID;
		item["key"] = unit.m_TF_Key;
		item["time"] = (int)unit.m_Tran_Time;
		item["open"] = unit.m_Open;
		item["high"] = unit.m_High;
		item["low"] = unit.m_Low;
		item["close"] = unit.m_Close;
		item["position"] = unit.m_Positions;
		item["vol"] = unit.m_Volume;
		item["totalvol"] = unit.m_Volume_Total;
		item["totalamount"] = unit.m_Amount_Total;
		jsList.append(item);

		if (++count % 20 == 0)
		{
			jsRes["finish"] = 0;
			jsRes["list"] = jsList;

			QJsonDocument doc(jsRes);
			res.push_back(doc.toJson(QJsonDocument::Compact));

			QJsonObject emptyObj;
			QJsonArray emptyArr;
			jsRes.swap(emptyObj);
			jsList.swap(emptyArr);
		}
	}
	jsRes["finish"] = 1;
	jsRes["list"] = jsList;

	QJsonDocument doc(jsRes);
	res.push_back(doc.toJson(QJsonDocument::Compact));

	auto iter = m_reqs.equal_range(id.toStdString());
	for (auto iter2 = iter.first; iter2 != iter.second;)
	{
        if (iter2->second.m_webHandler == nullptr)
			iter2 = m_reqs.erase(iter2);
		else
		{
			for (const auto& str : res)
			{
                emit sendDataToWeb(iter2->second.m_frameId, iter2->second.m_sid, str, iter2->second.m_jsCb);
			}
			++iter2;
		}
	}
}

bool TFKLineReqHandler::parse(const QJsonObject& cmdObj)
{
	QJsonObject obj = cmdObj["cond"].toObject();
	m_id = obj["id"].toString().toStdString();
	int minute = obj["minute"].toInt();
	if (minute > 1)
		return false;

	m_key = getTfKey(m_id.c_str());
	if (m_key.empty())
		return false;

    log_info("KLINE REQ: %s, %s", m_id.c_str(), m_key.c_str());
	return true;
}
